package com.znyj.cloud.device.scheduled;

import org.apache.log4j.Logger;

import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.*;

/**
 * Created by xxx on 16/1/22.
 */
@Component
public class ScheduledTimer {
    private static final Logger LOG = Logger.getLogger(ScheduledTimer.class);

    private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(4);
    private Map<Integer, Future> futures = new ConcurrentHashMap<>();

    public Future getFuture(int deviceNumber) {
        return futures.get(deviceNumber);
    }

    public void addFuture(int deviceNumber, Future future) {
        futures.put(deviceNumber, future);
    }

    public void removeFuture(int deviceNumber) {
        if (futures.containsKey(deviceNumber)) {
            futures.get(deviceNumber).cancel(true);
            futures.remove(deviceNumber);
        }
    }

    public ScheduledExecutorService getScheduledExecutorService() {
        return this.scheduledExecutorService;
    }

    public Future schedule(Runnable command, long delay, TimeUnit unit) {
        Future future = null;
        try {
            future = scheduledExecutorService.schedule(command, delay, unit);
        } catch (RejectedExecutionException e) {
            LOG.error("ScheduledTimer reject!!!", e);
        } catch (NullPointerException e) {
            LOG.error("Command is null!", e);
        }
        return future;
    }
}
